﻿import com.gamemeal.mvc.*;
import com.gamemeal.mvc.datatype.*;
/**
 * @author colin
 */
class com.gamemeal.mvc.AbstractController implements IController {
	private var model:IModel;
	private var view:IView;
	private var tmpValues : Array;
	private var dataHandler:IDataHandler;
	private var dataHandlerModel:IDataHandler;
	
	public function AbstractController(view:IView){
		this.view = view;
		tmpValues = new Array();//{bind,value}
		
		dataHandler = new ViewDataHandler(view);
		dataHandlerModel = new ModelDataHandler();
		dataHandler.setSuccessor(dataHandlerModel);
	}
	
	private function setValue(modelField:MFObject,value:Object):Boolean{
		//add value to temporary array, then flush data to model in 1 time.
		if(dataHandler.getValue(modelField)!=value){
			tmpValues.push({bind:modelField,value:value});
			return true;
		}
		return false;
	}

	private function getValue(modelField:MFObject){
		return dataHandler.getValue(modelField);
	}

	public function updateModel():Void{
		var bindMap:Array = view.getValue();
		var b:Binding;
		//update all input to model.
		for(var i=0;i<bindMap.length;i++){
			b = bindMap[i];
			b.bind.value = b.view.getValue();
		}

		//update all processed output to model.
		//loop the temporay array to update model.
		for(var i=0;i<tmpValues.length;i++){
			tmpValues[i].bind.value = tmpValues[i].value;
		}
		tmpValues = new Array();
		view.refresh();
	}
}